package net.sourceforge.perforce.ui.action;

import com.google.common.collect.Lists;

import net.sourceforge.perforce.core.PerforceException;
import net.sourceforge.perforce.core.api.IPerforceServer;
import net.sourceforge.perforce.core.resources.IP4File;
import net.sourceforge.perforce.ui.PerforceUIPlugin;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;

import java.util.List;


public class CompareWithHaveAction extends CompareWithHeadAction {
  @SuppressWarnings("unused")
  // PerforceException
  protected String compareRevision(IPerforceServer server, IResource[] resources)
      throws PerforceException {
    return "have";
  }

  @Override
  protected IResource[] getSelectedResources() {
    List<IResource> list = Lists.newArrayList();
    IP4File[] files = getSelectedP4Files();
    for (int i = 0; i < files.length; i++) {
      if (files[i].getAction().equals("edit")) {
        try {
          String localFileName =
              files[i].getServer().where(files[i].getDepotFilename()).getLocalFilename();
          IPath path = new Path(localFileName);
          IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
          IFile file = root.getFileForLocation(path);
          if (file != null) list.add((IResource) file.getAdapter(IResource.class));
        } catch (PerforceException e) {
          PerforceUIPlugin.log(e.getStatus());
        }
      }
    }
    return list.toArray(new IResource[0]);
  }
}
